#coding:utf-8
import requests
import time
import os
import re
from lxml import etree
import json
import subprocess
from tqdm import tqdm   #进度条配置


# 防止因https证书问题报错

requests.packages.urllib3.disable_warnings()

ffmpegurl='/opt/homebrew/bin/ffmpeg'

proxies = {'https': '127.0.0.1:7890'}

headers = {

    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36',
    'Refer'
    'er': 'https://www.youtube.com/'
}



def mymkdir(filepath):
    #print(type(filepath))
    filepath = filepath.strip()
    filepath = filepath.rstrip("\\")
    isExists = os.path.exists(filepath)
    if isExists:
        #print(filepath + ' 目录已存在')
        return False
    else:
        os.makedirs(filepath)
        print('创建成功')
        return True

def combineVideoAudio(videopath,audiopath,outpath):
    print(ffmpegurl+" -loglevel quiet -i " + videopath + " -i " + audiopath + " -c copy "+ outpath)
    subprocess.call((ffmpegurl+" -loglevel quiet -i " + videopath + " -i " + audiopath + " -c copy "+ outpath).encode("utf-8").decode("utf-8"),shell=True)
    #os.remove(videopath)
    #os.remove(audiopath)


def fileDownload(homeurl,url, name, session=requests.session()):
    print('下载:',name)
    # 添加请求头键值对,写上 refered:请求来源
    headers.update({'Referer': homeurl})
    # 发送option请求服务器分配资源
    session.options(url=url, headers=headers,verify=False)
    #获取资源
    res = session.get(url=url, headers=headers,verify=False) 
    file_size = int(res.headers.get('Content-Length'))
    video_pbar = tqdm(total=file_size)
    with open(name,mode='wb') as fp:
        # 把视频分成 1024 * 1024 * 2 为等分的大小 进行遍历
        for chunk in res.iter_content(1024*1024*2):
            # 写入数据
            fp.write(chunk)
            # 更新进度条
            video_pbar.set_description(f'正在下载{name}中......')
            # 更新进度条长度
            video_pbar.update(1024*1024*2)
    print('下载完成',name)

def get_video(url,filepath):
    session = requests.session()
    session.proxies = proxies
    response = session.get(url=url,headers=headers,verify=False)
    #print(response.text)
    video_json=re.findall('var ytInitialPlayerResponse = (.*?);var',response.text)[0]
    #print(len(video_json))
    videoJson = json.loads(video_json)

    videoId=videoJson['videoDetails']['videoId']
    videoTitle=videoJson['videoDetails']['title']
    videoLength=videoJson['videoDetails']['lengthSeconds']
    videoURL=videoJson['streamingData']['adaptiveFormats'][0]['url']
    audioURL=videoJson['streamingData']['adaptiveFormats'][-2]['url']

    videoTitle = re.sub(r'[\/:|?*"<>]', '', videoTitle)

    print('videoId=',videoId)
    print('videoTitle=',videoTitle)
    #print('videoLength=',videoLength)
    #print('videoUrl=',videoURL)
    #print('audioUrl=',audioURL)

    print('正在下载 "'+videoTitle+'" 的视频····')
    fileDownload(homeurl=url,url=videoURL, name=filepath+videoId + '_Video.mp4', session=session)
    print('正在下载 "'+videoTitle+'" 的音频····')
    fileDownload(homeurl=url,url=videoURL, name=filepath+videoId + '_Audio.mp3', session=session)
    combineVideoAudio(filepath+videoId + '_Video.mp4',filepath+videoId + '_Audio.mp3',filepath+videoTitle + '.mp4')

def download_video(path):
    timepath=time.strftime('%Y/%m/%d/')
    timepath=r'./'+timepath+'video/youtube/'
    mymkdir(timepath)
    print('视频预存地址',timepath)
    video_url = 'https://www.youtube.com/watch?v=iocJc342Q8s'   
    if len(path) != 0:
        video_url=path

    get_video(video_url,timepath)

    # try:
    #     get_video(video_url,timepath)
    #     print('下载成功')
    # except Exception as e:
    #     print('下载失败',e)
    #     return False
    return True

if __name__=='__main__':
    #video_url=input('视频地址:')
    video_url='https://www.youtube.com/watch?v=ExqqdUXXdgA'
    video_url='https://www.youtube.com/watch?v=87Ehd2ms2-0'
    print(video_url)
    num=0
    while True:
        status=download_video(video_url)
        if status:
            break
        if num>1:
          break
        num=num+1
    print('结束')
